<?php

namespace App\Http\Controllers\Backend;

use App\Models\PermissionGroup;
use App\Http\Requests\Backend\PermissionGroupRequest;

class PermissionGroupController extends BaseController {

    public function index()
    {
        $permissionGroups = PermissionGroup::paginate(2);

        return view('backend.permission_group.index')->with('permissionGroups', $permissionGroups);
    }


    public function create()
    {
        return view('backend.permission_group.create');
    }

    public function store(PermissionGroupRequest $request)
    {
        $redirect = $request->get('redirect');

        $permissionGroup = new PermissionGroup();
        $permissionGroup->name         = $request->get('name');;
        $permissionGroup->display_name = $request->get('display_name');
        $permissionGroup->description  = $request->get('description');
        $success = $permissionGroup->save();

        if($success) {
            return $this->responseCreatedSuccess('权限组添加成功', ['redirect' => $redirect]);
        } else {
            return $this->responseCreatedFail('权限组添加失败');
        }
    }

    public function show($id)
    {
        $permissionGroup = PermissionGroup::findOrFail($id);

        return view('backend.permission_group.show')->with('permissionGroup', $permissionGroup);
    }

    public function update($id, PermissionGroupRequest $request)
    {
        $redirect = $request->get('redirect');

        $permissionGroup = PermissionGroup::findOrFail($id);
        $permissionGroup->name         = $request->get('name');;
        $permissionGroup->display_name = $request->get('display_name');
        $permissionGroup->description  = $request->get('description');
        $success = $permissionGroup->save();

        if ($redirect) {
            return response(['success' => ['redirect' => $redirect]]);
        } elseif ($success){
            return ['success' => 1];
        } else {
            return response(['error' => ['field' =>'', 'message' => '保存失败']], 422);
        }
    }

    public function destroy($id, PermissionGroupRequest $request)
    {
        $redirect = $request->get('redirect');

        $permissionGroup = PermissionGroup::findOrFail($id);
        $success = $permissionGroup->delete();

        if($success) {
            return $this->responseDeletedSuccess('权限组删除成功', ['redirect' => $redirect]);
        }else {
            return $this->responseDeletedFail('权限组删除失败');
        }
    }

}